package com.example.score.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * html转pdf 注意：运行前需要先安装 wkhtmltopdf 并加入path环境变量
 * 下载 https://wkhtmltopdf.org/downloads.html
 * 调用及参数设置 https://blog.csdn.net/x6582026/article/details/53835835
 * 中文乱码或者空白解决方法:
 * 如果wkhtmltopdf中文显示空白或者乱码方框
 * 打开windows c:\Windows\fonts\simsun.ttc拷贝到linux服务器/usr/share/fonts/目录下,再次生成pdf中文显示正常
 */
@Slf4j
public class WkhtmltopdfUtil {
    // wkhtmltopdf在系统中的路径
    //private static String toPdfTool = "D:\\谷歌浏览器下载\\资料\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
    private static String toPdfTool = "E:/YJFX/wkhtmltopdf/bin/wkhtmltopdf.exe";


    /**
     * html转pdf
     *
     * @param srcPath      html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath     pdf保存路径
     * @param name
     * @param pdfCoverUrl
     * @param pdfHeaderUrl
     * @param pdfFooterUrl
     * @param p3
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath, String name, String pdfCoverUrl, String pdfHeaderUrl, String pdfFooterUrl, String p3) {
        File file = new File(destPath);
        //如果pdf保存路径不存在，则创建路径
        if (!file.exists()) {
            file.mkdirs();
        }
        if (p3 != null) {
            destPath = destPath + p3;
        }
        StringBuilder cmd = new StringBuilder();
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            // 非windows 系统
            //toPdfTool = "D:\\谷歌浏览器下载\\资料\\wkhtmltopdf\\bin";
            toPdfTool = "/home/bsta/eq_load/wkhtmltopdf";
            //toPdfTool = System.getProperty("user.dir") + "/wkhtmltox";
        }
        cmd.append(toPdfTool + " ");
        cmd.append("--debug-javascript ");
        cmd.append("--enable-local-file-access ");
        cmd.append("--window-status myrandomstring ");
        if (pdfHeaderUrl != null && name != null) {
            cmd.append("--header-html " + pdfHeaderUrl + "?disciplines=" + name + " ");
            cmd.append("--header-right " + name + " ");
        }
        cmd.append("--header-left 百师联盟 ");
        cmd.append("--header-font-size 10 ");
        cmd.append("--header-line ");
        cmd.append("--header-spacing 2 ");
        cmd.append("--footer-spacing 2 ");
        cmd.append("--margin-top 15mm ");
        cmd.append("--margin-bottom 15mm ");
        cmd.append("--footer-line ");
        cmd.append("--page-offset 0 ");
        if (pdfFooterUrl != null && pdfCoverUrl != null) {
            cmd.append("--footer-html " + pdfFooterUrl + " ");
            cmd.append(pdfCoverUrl);
        }
        cmd.append(" ");
        cmd.append("\"" + srcPath + "\"");
        cmd.append(" ");
        cmd.append("\"" + destPath + "\"");
        log.info("请求参数：" + cmd);
        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(String.valueOf(cmd));
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }


    public static boolean convert2(String srcPath, String destPath) {
//        File file = new File(destPath);
//        File parent = file.getParentFile();
        //如果pdf保存路径不存在，则创建路径
//        if(!parent.exists()){
//            parent.mkdirs();
//        }
        // 非windows 系统
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            // 非windows 系统
            //toPdfTool = "D:\\谷歌浏览器下载\\资料\\wkhtmltopdf\\bin";
            toPdfTool = "/home/bsta/jar/wkhtmltopdf";
            //toPdfTool = System.getProperty("user.dir") + "/wkhtmltox";
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(toPdfTool);
        cmd.append(" --debug-javascript ");
        cmd.append(" --enable-javascript ");
//        cmd.append(" --window-status test ");
//        cmd.append(" --load-error-handling ignore ");
//        cmd.append(" --enable-local-file-access ");
        cmd.append("\"" + srcPath + "\"");
        cmd.append(" ");
        cmd.append("\"" + destPath + "\"");
        log.info("请求参数：" + cmd);
//        boolean result = true;
//        try {
//            Process proc = Runtime.getRuntime().exec(cmd.toString());
//            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
//            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
//            error.start();
//            output.start();
//            proc.waitFor();
//        } catch (Exception e) {
//            result = false;
//            e.printStackTrace();
//        }
        return executeCommand(cmd.toString());
    }


    public static boolean executeCommand(String cmd) {
        boolean result = true;
        if (cmd == null || cmd.trim().isEmpty()) {
            System.err.println("Command is null or empty.");
            return false;
        }
        Process proc = null;
        try {
            // 使用 ProcessBuilder 执行命令
            if (System.getProperty("os.name").indexOf("Windows") == -1) {
                ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", cmd);
                proc = processBuilder.start();
            }else {
                proc = Runtime.getRuntime().exec(cmd.toString());
            }
            // 处理错误输出流
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                System.err.println("Error: " + errorLine);
            }

            // 处理标准输出流
            BufferedReader outputReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String outputLine;
            while ((outputLine = outputReader.readLine()) != null) {
                System.out.println("Output: " + outputLine);
            }

            // 设置超时时间
            if (!proc.waitFor(60, TimeUnit.SECONDS)) {
                // 超时处理
                proc.destroyForcibly();
                result = false;
                System.err.println("Command execution timed out.");
            }
        } catch (IOException e) {
            result = false;
            System.err.println("IO error occurred while executing the command: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            result = false;
            System.err.println("Thread was interrupted while waiting for the command to finish: " + e.getMessage());
            Thread.currentThread().interrupt();
        } finally {
            if (proc != null) {
                proc.destroy();
            }
        }
        return result;
    }

    public static class HtmlToPdfInterceptor extends Thread {
        private InputStream is;

        public HtmlToPdfInterceptor(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    log.info(line.toString()); //输出内容
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}